using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace ThaiLanguageTools.DataStruct
{
    /// <summary>
    /// Many-to-many mapping of strings
    /// </summary>
    public class StringMapping
    {
        [XmlElement("Comment")]
        public String Comment;

        [XmlElement("Entry")]
        public List<StringMappingEntry> Entries = new List<StringMappingEntry>();

        [XmlIgnore]
        MultiDictionary<String, String> _indexByA = new MultiDictionary<string,string>();
        [XmlIgnore]
        MultiDictionary<String, String> _indexByB = new MultiDictionary<string,string>();

        public StringMapping() { } // XML

        public void Add(String a, String b)
        {
            Entries.Add(new StringMappingEntry(a, b));
            _indexByA.Add(a, b);
            _indexByB.Add(b, a);
        }

        public List<String> GetMappingsByA(String keyA) { return _indexByA[keyA]; }
        public List<String> GetMappingsByB(String keyB) { return _indexByB[keyB]; }

        void Reindex()
        {
            _indexByA.Clear();
            _indexByB.Clear();
            foreach (StringMappingEntry e in Entries)
            {
                _indexByA.Add(e.A, e.B);
                _indexByB.Add(e.B, e.A);
            }
        }

        public static StringMapping Load(String file)
        {
            StringMapping sm = Utils.LoadXml<StringMapping>(file);
            sm.Reindex();
            return sm;
        }

        public void Save(String file)
        {
            Utils.SaveXml<StringMapping>(file, this);
        }
    }

    public class StringMappingEntry
    {
        [XmlAttribute("a")]
        public String A;
        [XmlAttribute("b")]
        public String B;
        public StringMappingEntry() { } // XML
        public StringMappingEntry(String a, String b) { A = a; B = b; }
    }
}
